package cuishifeng.blog.markdown;


import java.util.Set;

import javax.validation.constraints.NotNull;

import com.vladsch.flexmark.ast.Image;
import com.vladsch.flexmark.ast.Node;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.html.LinkResolver;
import com.vladsch.flexmark.html.LinkResolverFactory;
import com.vladsch.flexmark.html.renderer.LinkResolverContext;
import com.vladsch.flexmark.html.renderer.LinkStatus;
import com.vladsch.flexmark.html.renderer.ResolvedLink;
import com.vladsch.flexmark.util.options.MutableDataHolder;

/**
 * @author cuishifeng
 */
public class ImageUrlExtension implements HtmlRenderer.HtmlRendererExtension {


    public static final String MD_LOG_IMAGE_PREFIX = ".";
    public static final String MD_LOG_IMAGE_FILED_NAME = "images";

    @Override
    public void rendererOptions(MutableDataHolder options) {

    }

    @Override
    public void extend(HtmlRenderer.Builder rendererBuilder, String rendererType) {
        rendererBuilder.linkResolverFactory(new ImageUrlResolver.Factory());
    }

    static ImageUrlExtension create() {
        return new ImageUrlExtension();
    }


    public static class ImageUrlResolver implements LinkResolver {

        public ImageUrlResolver() {
        }

        @NotNull
        @Override
        public ResolvedLink resolveLink(@NotNull Node node, @NotNull LinkResolverContext context, @NotNull ResolvedLink link) {
            if (node instanceof Image && link.getUrl().startsWith(MD_LOG_IMAGE_PREFIX) && link.getUrl().contains(MD_LOG_IMAGE_FILED_NAME)) {
                String[] urls = link.getUrl().split("/");
                StringBuilder urlLinkBuilder = new StringBuilder();
                int startIndex = -1;
                for (int i = 0; i < urls.length; i++) {
                    if (urls[i].equals(MD_LOG_IMAGE_FILED_NAME)) {
                        startIndex = i;
                        urlLinkBuilder.append("/").append(urls[i]);
                    } else if (startIndex != -1 && i >= startIndex) {
                        urlLinkBuilder.append("/").append(urls[i]);
                    }
                }
                return link.withStatus(LinkStatus.VALID)
                        .withUrl(urlLinkBuilder.toString());
            }
            return link;
        }

        static class Factory implements LinkResolverFactory {

            @Override
            public Set<Class<? extends LinkResolverFactory>> getAfterDependents() {
                return null;
            }

            @Override
            public Set<Class<? extends LinkResolverFactory>> getBeforeDependents() {
                return null;
            }

            @Override
            public boolean affectsGlobalScope() {
                return false;
            }

            @Override
            public LinkResolver create(LinkResolverContext context) {
                return new ImageUrlResolver();
            }
        }
    }
}
